package com.imay.live.activity.user;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.bigkoo.quicksidebar.QuickSideBarView;
import com.bigkoo.quicksidebar.listener.OnQuickSideBarTouchListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.adapter.AreaAdapter;
import com.imay.live.model.AreaModel;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.Cn2Spell;
import com.imay.live.R;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by chan on 2017/3/28.
 */

public class LocalActivity extends UserBaseActivity implements OnQuickSideBarTouchListener {
    private List<AreaModel> areaModels;
    private RecyclerView mRecyclerView;
    private AreaModel areaModel;
    private AreaAdapter areaAdapter;
    private EditText editText;
    private QuickSideBarView mQuickSideBarView;
    private HashMap<String, Integer> letters = new HashMap<>();

    public static void startActivity(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, LocalActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_local;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.str_local_title));

        mRecyclerView = $(R.id.rv_local);
        mQuickSideBarView = (QuickSideBarView) findViewById(R.id.qsbv_local);
        try {
            areaModels = JSON.parseArray(AppUtil.getFromRaw(this, R.raw.area), AreaModel.class);

            ArrayList<String> customLetters = new ArrayList<>();

            int position = 0;
            for (AreaModel area : areaModels) {
                String letter = area.getAscription();
                //如果没有这个key则加入并把位置也加入
                if (!letters.containsKey(letter)) {
                    letters.put(letter, position);
                    customLetters.add(letter);
                }
                position++;
            }
            mQuickSideBarView.setLetters(customLetters);

            areaAdapter = new AreaAdapter(areaModels);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            mRecyclerView.setLayoutManager(layoutManager);
            StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(areaAdapter);
            mRecyclerView.addItemDecoration(headersDecor);
            mRecyclerView.setAdapter(areaAdapter);


            mQuickSideBarView.setOnQuickSideBarTouchListener(this);


            mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
                @Override
                public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (TextUtils.isEmpty(areaAdapter.getItem(position).getCode())) {
                        return;
                    }
                    Intent intent = getIntent();
                    intent.putExtra("local_text", areaAdapter.getItem(position).getCode() + "");
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            });

            mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                    .size(1)
                    .marginResId(R.dimen.item_top,R.dimen.item_top)
                    .build());

            editText = $(R.id.et_local_text);
            editText.addTextChangedListener(textWatcher);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            String str = s.toString();
            if (TextUtils.isEmpty(str)) {
                areaAdapter.setNewData(areaModels);
                areaAdapter.notifyDataSetChanged();
            } else {
                List<AreaModel> areas = search(str, areaModels);
                areaAdapter.setNewData(areas);
                areaAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }
    };

    private List<AreaModel> search(String name, List list) {
        List<AreaModel> result = new ArrayList<>();
        String strName = Cn2Spell.getPinYin(name);
        Pattern pattern = Pattern.compile(strName, Pattern.CASE_INSENSITIVE);
        for (int i = 0; i < list.size(); i++) {
            String str = Cn2Spell.getPinYin(((AreaModel) list.get(i)).getArea());
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                if(matcher.start() == 0){
                    result.add((AreaModel) list.get(i));
                }
            }
        }
        return result;
    }

    @Override
    public void onLetterChanged(String letter, int position, float y) {
        if (letters.containsKey(letter)) {
            LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView
                    .getLayoutManager();
            llm.scrollToPositionWithOffset(letters.get(letter), 0);//将指定的position滑动到距离上面第0个的位置，也就是顶部。
        }
    }

    @Override
    public void onLetterTouching(boolean touching) {

    }
}
